'use strict';

const moment = require('moment');
const common = require('../lib/common');
const userDb = require('../models/user');
const log =  require('../lib/log4js')();
const openIdList = require('../config/user').grantAuthsOpenId;

/* 获取二维码的信息代码 */
async function login(req, res){

  try{

    var params = JSON.parse(req.body);

    if ( openIdList.IndexOf(params.openId) > -1 ){

      var data = await userDb.findOne({where: {openId: params.openId}});
      var now = moment().format('YYYY-MM-DD HH:mm:ss');
      
      if (data == null){
          
        let ret = await userDb.create({
          openId: params.openId,
          unionId: params.unionId,
          source: params.source,
          env: params.env,
          type: 3,
          mobile: params.mobile,
          role: null,
          accode: params.accode,
          status: 1,
          loginCount: 1,
          loginTime: now,
          create: now
        });
  
      }else{
          
        let loginCount = data.loginCount + 1;
        let ret = await userDb.update({loginTime: now, loginCount: loginCount}, {where: {id: data.id}});
  
      };
  
      res.send({error: null,loginTime: now});

    }else{
      res.send({error: 'unauthorized user'});
    };

  }catch(error){
    log.error('api res:' + req.route.path + ' res error: ' + error.toString());
    res.send({error: error});
  };

};

module.exports = {
  login: login
};